<!DOCTYPE html>
<html lang="en">
<?php
// 启动会话
session_start();
?>

<script>
  function userIsLoggedIn() {
    // 在这里实现用户登录状态的检查逻辑
    // 返回值为布尔值，true 表示用户已登录，false 表示用户未登录
    // 示例：检查用户是否具有有效的登录凭据
    // 这里改为检查会话中的登录状态
    return <?php echo isset($_SESSION['loggedin']) && $_SESSION['loggedin'] ? 'true' : 'false'; ?>;
  }

  // 在页面加载时检查用户登录状态
  window.addEventListener('DOMContentLoaded', function() {
    if (!userIsLoggedIn()) {
      window.location.href = '../Login.php'; // 请将 'login.html' 替换为您实际的登录页面路径
    }
  });
</script>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>房间状态管理</title>
  <link href="../css/bootstrap.min530.css" rel="stylesheet">
  <link rel="stylesheet" href="../css/jquery-ui.css">
  <link rel="stylesheet" href="../css/jquery.datetimepicker.min.css">
  <link rel="stylesheet" href="../css/bootstrap.min441.css">
  <link href="../css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="../css/jquery-ui.css">
  <link rel="stylesheet" href="../css/bootstrap-select.css">
  <style>
    .room-status {
      font-weight: bold;
    }

    .room-number {
      color: #4CAF50;
    }

    .room-type {
      text-transform: uppercase;
    }

    .cleanliness {
      background-color: #F06292;
    }

    .cleaner {
      color: #2196F3;
    }

    .qualified {
      font-style: italic;
    }

    .sellable {
      font-weight: bold;
      color: #FFC107;
    }

    .lastcleaned {
      font-size: 16px;
    }
  </style>




</head>
</head>

<body>
  <div class="container">
    <!-- 预定管理 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <a class="navbar-brand" href="#">酒店后台管理系统</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
          <li class="nav-item ">
            <a class="nav-link" href="./预购订单管理.php">预订管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./房态查询页面.php">房态查询<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item active">
            <a class="nav-link" href="./房间状态管理.php">房态管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./后台房源管理页面.php">房源管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./客户管理页面.php">客户管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item ">
            <a class="nav-link" href="./账户管理页面.php">账户管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./留言后台查看界面.php">留言管理<span class="sr-only">(current)</span></a>
          </li>


          <li class="nav-item">
            <a class="nav-link" href="../backend01.php">退回主页<span class="sr-only">(current)</span></a>
          </li>

          <li class="nav-item">
            <a class="nav-link" href="./数据库连接示意.php">测试连接<span class="sr-only">(current)</span></a>
          </li>

        </ul>
      </div>
    </nav>
    <div class="container mt-4">
      <h2>添加房间状态</h2>
      <h4>这是作为添加新房间时使用,日常管理请使用下面模块</h4>
      <hr>
      <form id="roomForm">
        <div class="row">
          <div class="form-group col-md-3">
            <label for="roomNumber">房间号</label>
            <input type="text" class="form-control" id="roomNumber" placeholder="输入房间号">
          </div>
          <div class="form-group col-md-3">
            <label for="roomType">房间类型</label>
            <select class="form-control" id="roomType">
              <option value="大床房">大床房</option>
              <option value="双人房">双人房</option>
              <option value="情侣房">情侣房</option>
              <option value="家庭套房">家庭套房</option>
              <option value="蜜月套房">蜜月套房</option>
            </select>
          </div>
          <div class="form-group col-md-3">
            <label for="status">占用情况</label>
            <select class="form-control" id="status">
              <option value="未退房">未退房</option>
              <option value="已退房">已退房</option>
            </select>
          </div>
          <div class="form-group col-md-3">
            <label for="cleanliness">清洁情况</label>
            <select class="form-control" id="cleanliness">
              <option value="未清洁">未清洁</option>
              <option value="已清洁">已清洁</option>
            </select>
          </div>
        </div>
        <div class="row">
          <div class="form-group col-md-3">
            <label for="cleaner">打扫人员</label>
            <select class="form-control" id="cleaner">
              <option value="宋瑾">宋瑾</option>
              <option value="沈慕容">沈慕容</option>
              <option value="董紫陌">董紫陌</option>
              <option value="卓夜白">卓夜白</option>
              <option value="崔霜">崔霜</option>
            </select>
          </div>
          <div class="form-group col-md-3">
            <label for="qualified">合格情况</label>
            <select class="form-control" id="qualified">
              <option value="合格">合格</option>
              <option value="不合格">不合格</option>
            </select>
          </div>
          <div class="form-group col-md-3">
            <label for="sellable">出售情况</label>
            <select class="form-control" id="sellable">
              <option value="可出售">可出售</option>
              <option value="禁止出售">禁止出售</option>
            </select>
          </div>
          <div class="form-group col-md-3">
            <label for="lastCleaned">本次清洁时间</label>
            <input type="text" class="form-control" id="lastCleaned" placeholder="输入本次清洁时间">
          </div>
        </div>


        <button type="submit" class="btn btn-primary">提交</button>
      </form>
      <table class="table">
        <h2>所有房间</h2>
        <thead>
          <tr>
            <th>房间id</th>
            <th>房间号</th>
            <th>房间类型</th>
            <th>占用情况</th>
            <th>清洁情况</th>
            <th>打扫人员</th>
            <th>合格情况</th>
            <th>出售情况</th>
            <th>上次清洁时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody id="data-table">
          <!-- 房间列表内容通过后台数据动态生成 -->
        </tbody>
      </table>

    </div>
    <!-- 模态框 -->
    <div class="modal" id="updateModal" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">更新数据</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form id="updateForm">
              <div class="form-group col-md-6">
                <label for="Status">占用情况</label>
                <select class="form-control" id="Status">
                  <option value="未退房">未退房</option>
                  <option value="已退房">已退房</option>
                </select>
              </div>
              <div class="form-group col-md-6">
                <label for="Cleanliness">清洁情况</label>
                <select class="form-control" id="Cleanliness">
                  <option value="未清洁">未清洁</option>
                  <option value="已清洁">已清洁</option>
                </select>
              </div>
              <div class="form-group col-md-6">
                <label for="Cleaner">打扫人员</label>
                <select class="form-control" id="Cleaner">
                  <option value="宋瑾">宋瑾</option>
                  <option value="沈慕容">沈慕容</option>
                  <option value="董紫陌">董紫陌</option>
                  <option value="卓夜白">卓夜白</option>
                  <option value="崔霜">崔霜</option>
                </select>
              </div>
              <div class="form-group col-md-6">
                <label for="Qualified">合格情况</label>
                <select class="form-control" id="Qualified">
                  <option value="合格">合格</option>
                  <option value="不合格">不合格</option>
                </select>
              </div>
              <div class="form-group col-md-6">
                <label for="Sellable">能否出售</label>
                <select class="form-control" id="Sellable">
                  <option value="可出售">可出售</option>
                  <option value="禁止出售">禁止出售</option>
                </select>
              </div>
              <div class="form-group col-md-6">
                <label for="LastCleaned">本次清洁时间</label>
                <input type="text" class="form-control" id="LastCleaned" placeholder="输入本次清洁时间">
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-success" id="updateStatusBtn">房间状态</button>
            <button type="button" class="btn btn-info" id="updateCleanlinessBtn">清洁状态</button>
            <button type="button" class="btn btn-warning" id="updateCleanerBtn">清洁人员</button>
            <button type="button" class="btn btn-danger" id="updateQualificationBtn">合格状态</button>
            <button type="button" class="btn btn-info" id="updateSaleabilityBtn">能否销售</button>
            <button type="button" class="btn btn-primary" id="updateTimeBtn">更新时间</button>
            <button type="button" class="btn btn-success" id="updateDataBtn">更新</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
          </div>
        </div>
      </div>
    </div>

    <script src="../js/jquery-3.6.0.min.js"></script>
    <script src="../js/jquery-ui.js"></script>
    <script src="../js/bootstrap.min441.js"></script>
    <script src="../js/jquery.datetimepicker.full.min.js"></script>
    <script>
      $(function() {
        $("#lastCleaned").datetimepicker({
          format: 'Y-m-d H:i:s', // 设置日期时间格式
          step: 60 // 设置时间步长为60分钟，即精确到小时
        });
      });
      $(function() {
        $("#LastCleaned").datetimepicker({
          format: 'Y-m-d H:i:s', // 设置日期时间格式
          step: 60 // 设置时间步长为60分钟，即精确到小时
        });
      });
    </script>
    <script>
      $(document).ready(function() {
        $('#roomForm').submit(function(event) {
          event.preventDefault(); // 阻止表单的默认提交行为

          // 执行表单验证逻辑
          if (validateForm()) {
            // 表单验证通过，继续提交
            submitForm();
          }
        });
      });

      function validateForm() {
        // 获取表单输入的值
        var roomNumber = $('#roomNumber').val();
        var roomType = $('#roomType').val();
        var status = $('#status').val();
        var cleanliness = $('#cleanliness').val();
        var cleaner = $('#cleaner').val();
        var qualified = $('#qualified').val();
        var sellable = $('#sellable').val();
        var lastCleaned = $('#lastCleaned').val();
        // 添加适当的表单验证规则
        if (!roomNumber) {
          alert('请填写房间号');
          return false; // 表单验证失败
        }
        if (!roomType) {
          alert('请填写房间类型');
          return false; // 表单验证失败
        }
        if (!status) {
          alert('请填写房间状态');
          return false; // 表单验证失败
        }
        if (!cleanliness) {
          alert('请填写清洁度');
          return false; // 表单验证失败
        }
        if (!cleaner) {
          alert('请填写清洁人员');
          return false; // 表单验证失败
        }
        if (!lastCleaned) {
          alert('请填写最后清理时间');
          return false; // 表单验证失败
        }
        // 可以添加其他必填字段的验证规则
        // 可以添加其他验证逻辑，例如检查输入值的长度、格式等
        return true; // 表单验证通过
      }

      function submitForm() {
        // 获取表单数据
        var roomNumber = $('#roomNumber').val();
        var roomType = $('#roomType').val();
        var status = $('#status').val();
        var cleanliness = $('#cleanliness').val();
        var cleaner = $('#cleaner').val();
        var qualified = $('#qualified').val();
        var sellable = $('#sellable').val();
        var lastCleaned = $('#lastCleaned').val();
        // 测试
        console.log('提交的房间状态数据:', {
          roomNumber: roomNumber,
          roomType: roomType,
          status: status,
          cleanliness: cleanliness,
          cleaner: cleaner,
          qualified: qualified,
          sellable: sellable,
          lastCleaned: lastCleaned
        });
        // 创建 FormData 对象
        var formData = new FormData();
        formData.append('roomNumber', roomNumber);
        formData.append('roomType', roomType);
        formData.append('status', status);
        formData.append('cleanliness', cleanliness);
        formData.append('cleaner', cleaner);
        formData.append('qualified', qualified);
        formData.append('sellable', sellable);
        formData.append('lastCleaned', lastCleaned);
        //使用Ajax发送表单数据到后端PHP处理
        $.ajax({
          url: '../backend/api/roomStatusManagement_1.php', // 后端PHP脚本的URL，根据您的实际配置进行调整
          data: formData,
          type: 'POST',
          processData: false,
          contentType: false,
          success: function(response) {
            console.log('后端处理结果:', response.message);
            console.log('新记录ID:', response.newRecordId);
            $('#roomForm')[0].reset();
          },
          error: function(xhr, status, error) {
            // 处理Ajax请求错误
            console.error('Ajax请求错误:', error);
          }
        });
      }
    </script>


    <script>
      // 绑定关闭模态框事件
      $("#myModal").on("hidden.bs.modal", function(event) {
        // 清空表单数据
        $("#modal-form")[0].reset();
        // 清空表单验证状态
        $("#modal-form").validate().resetForm();
      });
      $(document).ready(function() {
        // 发起 AJAX 请求获取数据
        $.ajax({
          url: '../backend/api/roomStatusManagement_2.php',
          type: 'GET',
          dataType: 'json',
          success: function(data) {
            // 动态生成数据列表
            var table = $('#data-table');
            // 清空tbody内容
            table.empty();
            // 添加数据行
            $.each(data, function(index, item) {
              var tr = $('<tr>').appendTo(table);
              $('<td>').text(item.roomstatus_id).addClass('room-status').appendTo(tr);
              $('<td>').text(item.number).addClass('room-number').appendTo(tr);
              $('<td>').text(item.roomType).addClass('room-type').appendTo(tr);
              $('<td>').text(item.status).addClass('status').appendTo(tr);
              $('<td>').text(item.cleanliness).addClass('cleanliness').appendTo(tr);
              $('<td>').text(item.cleaner).addClass('cleaner').appendTo(tr);
              $('<td>').text(item.qualified).addClass('qualified').appendTo(tr);
              $('<td>').text(item.sellable).addClass('sellable').appendTo(tr);
              $('<td>').text(item.lastCleaned).addClass('lastcleaned').appendTo(tr);
              var button = $('<button>').text('更新').addClass('btn-success').appendTo($('<td>').appendTo(tr));
              var deleteBtn = $('<button>').text('删除').addClass('btn-danger').appendTo($('<td>').appendTo(tr));
              // 删除代码的操作
              deleteBtn.click(function() {
                var currentRow = $(this).closest('tr');
                var roomId = currentRow.find('.room-status').text();
                // 确认是否删除
                if (confirm('确定要删除ID为 ' + roomId + ' 的房间吗？请注意，删除操作为不可逆操作！')) {
                  // 发送Ajax请求将数据从数据库中删除
                  $.ajax({
                    method: 'POST',
                    url: '../backend/api/roomStatusManagement_4.php',
                    data: {
                      id: roomId
                    },
                    dataType: 'json', // 设置dataType为'json'
                    success: function(data) {
                      // 如果删除成功，从页面上删除该行数据
                      currentRow.remove();
                      // 生成日志
                      generateLog(roomId);
                      alert('删除成功！');
                    },
                    error: function(xhr, status, error) {
                      // 如果删除失败，显示错误信息
                      console.log('删除失败：' + error);
                    }
                  });
                };
              });

              function generateLog(roomId) {
                // 创建日志对象
                var log = {
                  room: roomId,
                  action: '删除',
                  deleteTime: new Date().toISOString(),
                  time: new Date().toISOString()
                };

                // 发送Ajax请求将日志信息保存到服务器
                $.ajax({
                  url: '../backend/api/roomStatusManagement_5_generateLog.php',
                  method: 'POST',
                  data: log,
                  // 日志文件有问题，但不妨碍主要功能
                  success: function(data) {
                    console.log('日志生成成功！');
                  },
                  error: function(xhr, status, error) {
                    //  console.log('日志生成失败：' + error);
                  }
                });
              }
              button.click(function() {
                var status = tr.find('.status').text();
                var cleanliness = tr.find('.cleanliness').text();
                var cleaner = tr.find('.cleaner').text();
                var qualified = tr.find('.qualified').text();
                var sellable = tr.find('.sellable').text();
                var lastcleaned = tr.find('.lastcleaned').text();
                // 将数据填充到模态框中
                $('#updateModal #Status').val(status);
                $('#updateModal #Cleanliness').val(cleanliness);
                $('#updateModal #Cleaner').val(cleaner);
                $('#updateModal #Qualified').val(qualified);
                $('#updateModal #Sellable').val(sellable);
                $('#updateModal #LastCleaned').val(lastcleaned);
                // 弹出模态框
                // 获取模态框对象
                var updateModal = document.getElementById('updateModal');
                // 创建模态框对象
                var modal = new bootstrap.Modal(updateModal);
                // 弹出模态框
                modal.show();
                // 模态框的按钮快捷更改状态
                $(document).ready(function() {
                  // 更新房间状态
                  // 更新房间状态
                  // 模拟修改房间状态功能
                  $('#updateStatusBtn').click(function() {
                    var status = $('#Status').val();
                    changeRoomStatus(status); // 调用状态切换函数，传入当前选择的状态
                  });
                  // 修改房间状态的函数，使用状态选项对象进行状态切换
                  function changeRoomStatus(currentStatus) {
                    //  定义了一个名为roomStatusOptions的对象，包含不同的房间状态选项
                    var roomStatusOptions = {
                      '未退房': '已退房',
                      '已退房': '未退房'
                    };
                    var nextStatus = roomStatusOptions[currentStatus];
                    // 将下一个状态填充到输入框中
                    $('#Status').val(nextStatus);
                  }
                  // 更新状态
                  // 更新状态
                  $('#updateCleanlinessBtn').click(function() {
                    var cleanliness = $('#Cleanliness').val();
                    changeRoomCleanliness(cleanliness); // 调用清洁度切换函数，传入当前选择的状态
                  });

                  function changeRoomCleanliness(currentCleanliness) {
                    //  定义了一个名为roomCleanlinessOptions的对象，包含不同的清洁度选项
                    var roomCleanlinessOptions = {
                      '未清洁': '已清洁',
                      '已清洁': '未清洁'
                    };
                    var nextCleanliness = roomCleanlinessOptions[currentCleanliness];
                    // 将下一个清洁度填充到输入框中
                    $('#Cleanliness').val(nextCleanliness);
                  }
                  // 更新清洁人员
                  // 更新清洁人员
                  $('#updateCleanerBtn').click(function() {
                    var cleaners = ['宋瑾', '沈慕容', '董紫陌', '卓夜白', '崔霜'];
                    var currentCleaner = $('#Cleaner').val();
                    var index = cleaners.indexOf(currentCleaner);
                    var nextCleaner = cleaners[(index + 1) % cleaners.length];
                    $('#Cleaner').val(nextCleaner);
                  });
                  // 更新合格状态
                  // 更新合格状态
                  $('#updateQualificationBtn').click(function() {
                    var currentStatus = $('#Qualified').val();
                    var updatedStatus = currentStatus === '合格' ? '不合格' : '合格';
                    $('#Qualified').val(updatedStatus);
                  });
                  // 更新是否可销售
                  // 更新是否可销售
                  $('#updateSaleabilityBtn').click(function() {
                    var status = $('#Status').val();
                    var cleanliness = $('#Cleanliness').val();
                    var qualified = $('#Qualified').val();
                    var currentStatus = $('#Sellable').val();

                    if (status !== '未退房' && cleanliness !== '未清洁' && qualified !== '不合格') {
                      var updatedStatus = (currentStatus === '可出售') ? '禁止出售' : '可出售';
                      $('#Sellable').val(updatedStatus);
                    } else {
                      alert('无法改变出售情况，因为占用情况、清洁情况或合格情况不符合要求。');
                    }
                  });
                  // 更新时间情况
                  // 更新时间情况
                  $('#updateTimeBtn').click(function() {
                    var currentTime = new Date().toISOString().slice(0, 19).replace('T', ' '); // 获取当前时间并格式化
                    $('#LastCleaned').val(currentTime); // 将当前时间设置为输入框的值
                  });
                });
                // // 更新数据按钮的点击事件
                $(document).ready(function() {
                  // 更新数据按钮的点击事件
                  $('#updateDataBtn').click(function() {
                    var updatedStatus = $('#updateModal #Status').val();
                    var updatedCleanliness = $('#updateModal #Cleanliness').val();
                    var updatedCleaner = $('#updateModal #Cleaner').val();
                    var updatedQualified = $('#updateModal #Qualified').val();
                    var updatedSellable = $('#updateModal #Sellable').val();
                    var updatedLastcleaned = $('#updateModal #LastCleaned').val();
                    console.log(updatedLastcleaned);
                    // 更新数据库
                    $.ajax({
                      url: '../backend/api/roomStatusManagement_3.php',
                      method: 'POST',
                      data: {
                        roomstatus_id: item.roomstatus_id,
                        status: updatedStatus,
                        cleanliness: updatedCleanliness,
                        cleaner: updatedCleaner,
                        qualified: updatedQualified,
                        sellable: updatedSellable,
                        lastcleaned: updatedLastcleaned
                      },
                      success: function(response) {
                        if (response.status === 'success') {
                          console.log('数据已成功更新！');
                          // 更新对应的数据行内容
                          var rowToUpdate = $('tr[data-roomstatus-id="' + item.roomstatus_id + '"]');
                          rowToUpdate.find('.status').text(updatedStatus);
                          rowToUpdate.find('.cleanliness').text(updatedCleanliness);
                          rowToUpdate.find('.cleaner').text(updatedCleaner);
                          rowToUpdate.find('.qualified').text(updatedQualified);
                          rowToUpdate.find('.sellable').text(updatedSellable);
                          rowToUpdate.find('.lastcleaned').text(updatedLastcleaned);
                          // 关闭模态框
                          // 关闭模态框
                          $("#updateModal").modal("hide");
                        } else {
                          console.log('数据更新失败');
                        }
                      }
                    });
                  });
                });
              });
            });
          }
        })
      })
    </script>
</body>

</html>